package com.yby.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yby.common.utils.PageUtils;
import com.yby.common.utils.R;
import com.yby.mall.product.dao.CategoryBrandRelationDao;
import com.yby.mall.product.dao.CategoryDao;
import com.yby.mall.product.entity.CategoryBrandRelationEntity;
import com.yby.mall.product.entity.CategoryEntity;
import com.yby.mall.product.vo.BrandVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yby.common.utils.Query;

import com.yby.mall.product.dao.BrandDao;
import com.yby.mall.product.entity.BrandEntity;
import com.yby.mall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;


    @Override
    public R queryPage(Integer page, Integer limit, String key) {
        PageHelper.startPage(page,limit);
        List<BrandEntity> list = brandDao.selectList(Wrappers.<BrandEntity>lambdaQuery()
                .like(!StringUtils.isEmpty(key), BrandEntity::getName, key));
        return R.ok().put("page", PageUtils.restPage(list));
    }

    @Override
    @Transactional
    public R delete(List<Long> asList) {
        brandDao.deleteBatchIds(asList);
        asList.stream().forEach(brandId->{
            categoryBrandRelationDao.delete(Wrappers.<CategoryBrandRelationEntity>lambdaQuery().eq(CategoryBrandRelationEntity::getBrandId,brandId));
        });
        return R.ok();
    }

    @Override
    public R updateStatus(Map<String, Object> map) {
        int brandId = Integer.parseInt(map.get("brandId").toString());
        int showStatus = Integer.parseInt(map.get("showStatus").toString());
        brandDao.updateByShowStatus(brandId,showStatus);
        return null;
    }

    @Override
    @Transactional
    public R updateByBrand(BrandVo brandVo) {
        BrandEntity brandEntity = new BrandEntity();
        BeanUtils.copyProperties(brandVo,brandEntity);
        brandDao.updateById(brandEntity);
        //修改品牌分类表里面的品牌名称字段
        categoryBrandRelationDao.updateByBrandName(brandVo.getBrandId(),brandVo.getName());
        return R.ok();
    }
}